package cc.lzmsh.service.impl;

import cc.lzmsh.mapper.ArticleMapper;
import cc.lzmsh.pojo.Article;
import cc.lzmsh.pojo.result.PageBean;
import cc.lzmsh.pojo.result.Result;
import cc.lzmsh.service.ArticleService;
import cc.lzmsh.utils.AliOssUtil;
import cc.lzmsh.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Author:   msh
 * Date:     2024/9/26 下午2:42
 * Description:
 */

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public Result addArticle(Article article) {
        Map<String, Object> map = ThreadLocalUtil.get();
        article.setCreateUser((Integer) map.get("userId"));
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        if (article.getCoverImg() == null){
            return Result.error("封面图不能为空");
        }
        if (article.getTitle() == null || article.getTitle().equals("")){
            return Result.error("标题不能为空");
        }
        if (article.getContent() == null || article.getContent().equals("")){
            return Result.error("内容不能为空");
        }
        if (article.getCategoryId() == null){
            return Result.error("分类不能为空");
        }
        articleMapper.addArticle(article);
        return Result.success();
    }

    @Override
    public Result<PageBean<Article>> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        // 分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleMapper.list(userId,categoryId, state);
        Page<Article> articles = (Page<Article>) articleList;
        return Result.success(new PageBean<>(articles.getTotal(),articles.getResult()));
    }

    @Override
    public Result getArticleById(Integer id) {
        return Result.success(articleMapper.getArticleById(id));
    }

    @Override
    public Result updateArticle(Article article) {
        articleMapper.updateArticle(article);
        return Result.success();
    }

    @Override
    public Result deleteArticle(Integer id) {
        articleMapper.deleteArticle(id);
        return Result.success();
    }

    @Override
    public Result upload(String fileName, InputStream inputStream) {
        return Result.success(AliOssUtil.upload(fileName,inputStream));
    }


}
